package userInterface;
import dataProces.DatabaseOperations;

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;

public class Withdrawal extends JDialog implements ActionListener {
    JPanel[] jPanels = new JPanel[3];
    JTextField[] jFields = new JTextField[2];
    JButton[] jButtons = new JButton[3];
    String[] prompt = { "取款", "查询", "返回", "取款界面" };

    public Withdrawal() {
        Container container = this.getContentPane();
        container.setLayout(new GridLayout(5, 1));
        for (int i = 0; i < jPanels.length; i++) {
            jPanels[i] = new JPanel();
            jButtons[i] = new JButton(prompt[i]);
            jButtons[i].addActionListener(this);
            jPanels[i].add(jButtons[i]);
            if (i < 2) {
                jFields[i] = new JTextField(15);
                if (i == 1)
                    jFields[i].setEditable(false);
                jPanels[i].add(jFields[i]);
            }
            container.add(jPanels[i]);
        }
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setSize(500, 300);
        Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
        setLocation((screen.width - 500) / 2, (screen.height - 300) / 2);
        setTitle(prompt[3]);
        setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {
        DatabaseOperations dOperations = new DatabaseOperations();
        if (e.getSource() == jButtons[0]) {
            double money = Double.parseDouble(dOperations.dataQueries("investment", Login.user, "money"));
            double fund = Double.parseDouble(jFields[0].getText().trim());
            if (fund <= money) {
                money -= fund;
                dOperations.dataUpdates("investment", Login.user, "money", String.format("%.2f", money));
                JOptionPane.showMessageDialog(null, "取款"+fund+"元！");
            } else
                JOptionPane.showMessageDialog(null, "账户余额不足！");
            dispose();
            new Withdrawal();
        } else if (e.getSource() == jButtons[1]) {
            String money = dOperations.dataQueries("investment", Login.user, "money");
            jFields[1].setText(money);
        } else if (e.getSource() == jButtons[2]) {
            dispose();
            new UserMenu();
        }
    }

    public static void main(String[] args) {
        new Withdrawal();
    }
}
